package com.zay.a5_buttons;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zay.a5_buttons.pojo.User;

public class LoginActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Button btn_login=findViewById(R.id.btn_login);
        Button btn_zhuce=findViewById(R.id.btn_zhuce);
        EditText userName=findViewById(R.id.username);
        EditText passWord=findViewById(R.id.password);
        btn_login.setOnClickListener(view -> {
            String username = userName.getText().toString();
            String password = passWord.getText().toString();
            if("".equals(username)||"".equals(password)){
                Toast.makeText(LoginActivity.this,"用户名或密码不能为空",Toast.LENGTH_SHORT).show();
                return;
            }
            User user=new User(username,password);
            if(selectUserFormDb(user)){
                Intent intent = new Intent(LoginActivity.this,ShowActivity.class);
                intent.putExtra("username",username);
                intent.putExtra("password",password);
                startActivity(intent);
                finish();
            }else{
                Toast.makeText(LoginActivity.this,"密码错误",Toast.LENGTH_SHORT).show();
            }
        });
        btn_zhuce.setOnClickListener(view -> {
            Intent intent=new Intent(LoginActivity.this,ZhuCeActivity.class);
            startActivity(intent);
        });
    }
    @SuppressLint("Range")
    public boolean selectUserFormDb(User user){
        // 创建DatabaseHelper对象
        MySQLiteOpenHelper dbHelper = new MySQLiteOpenHelper(LoginActivity.this,"user_tab",null,1);
        // 调用getWritableDatabase()方法创建或打开一个可以读的数据库
        SQLiteDatabase sqLiteDatabase = dbHelper.getReadableDatabase();
        //游标,为查询数据库返回的结果
        Cursor cursor=sqLiteDatabase.query("user_tab", new String[]{"uAccount","uPassword"},"uAccount like ?",new String[]{user.getuAccount()},null,
                null,null);
        if (cursor.moveToNext()){
            String uAccount=cursor.getString(cursor.getColumnIndex("uAccount"));
            String uPassword=cursor.getString(cursor.getColumnIndex("uPassword"));
            return uAccount.equals(user.getuAccount()) && uPassword.equals(user.getuPassword());
        }else {
            Toast.makeText(LoginActivity.this,"未查到该账号，请重新输入",Toast.LENGTH_SHORT).show();
        }
        cursor.close();
        sqLiteDatabase.close();
        return false;
    }
}